<template>
  <div class="search-container">
    <div class="search-header">
      <h2>文献搜索</h2>
      <p>智能检索您的医学文献资源</p>
    </div>

    <!-- 搜索框 -->
    <div class="search-box">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入搜索关键词..."
        size="large"
        @keyup.enter="performSearch"
        clearable
      >
        <template #prepend>
          <el-select v-model="searchType" style="width: 120px">
            <el-option label="综合搜索" value="all"></el-option>
            <el-option label="标题" value="title"></el-option>
            <el-option label="作者" value="author"></el-option>
            <el-option label="关键词" value="keyword"></el-option>
          </el-select>
        </template>
        <template #append>
          <el-button type="primary" @click="performSearch" :loading="searching">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 热门搜索和搜索历史 -->
    <el-row :gutter="20" class="search-assist">
      <el-col :span="12" :xs="24">
        <el-card class="hot-search-card">
          <template #header>
            <div class="card-header">
              <span>热门搜索</span>
            </div>
          </template>
          <div class="hot-keywords">
            <el-tag 
              v-for="(keyword, index) in hotKeywords" 
              :key="index"
              class="hot-keyword"
              type="primary"
              effect="dark"
              @click="searchByKeyword(keyword)"
            >
              {{ keyword }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>搜索历史</span>
              <el-button 
                type="text" 
                @click="clearHistory"
                :disabled="searchHistory.length === 0"
              >
                清空
              </el-button>
            </div>
          </template>
          <div class="search-history">
            <el-tag 
              v-for="(keyword, index) in searchHistory" 
              :key="index"
              class="history-keyword"
              type="info"
              @click="searchByKeyword(keyword)"
            >
              {{ keyword }}
            </el-tag>
            <div v-if="searchHistory.length === 0" class="empty-history">
              暂无搜索历史
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索结果 -->
    <div v-if="searchResults.length > 0 || searching" class="search-results">
      <el-card class="results-card">
        <template #header>
          <div class="results-header">
            <span>搜索结果 (共 {{ pagination.total }} 条)</span>
            <div class="sort-options">
              <el-select v-model="sortField" size="small" @change="performSearch">
                <el-option label="相关度" value="relevance"></el-option>
                <el-option label="时间" value="time"></el-option>
                <el-option label="引用次数" value="citation"></el-option>
              </el-select>
            </div>
          </div>
        </template>
        
        <div v-loading="searching" element-loading-text="搜索中...">
          <div 
            v-for="item in searchResults" 
            :key="item.id" 
            class="result-item"
            @click="viewDetail(item.id)"
          >
            <div class="result-title">
              <el-link type="primary" :underline="false">
                {{ item.title }}
              </el-link>
              <el-tag 
                v-if="item.isFavorite" 
                type="warning" 
                size="small"
                effect="dark"
              >
                已收藏
              </el-tag>
            </div>
            <div class="result-authors">
              {{ item.authors }}
            </div>
            <div class="result-abstract">
              {{ item.abstractText }}
            </div>
            <div class="result-meta">
              <span class="journal">{{ item.journal }}</span>
              <span class="date">{{ formatDate(item.publicationDate) }}</span>
              <span class="keywords">
                <el-tag 
                  v-for="keyword in item.keywords?.split(',').slice(0, 3)" 
                  :key="keyword" 
                  size="small"
                  type="success"
                >
                  {{ keyword }}
                </el-tag>
              </span>
            </div>
          </div>
          
          <!-- 分页 -->
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            class="pagination"
          />
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-if="searchResults.length === 0 && !searching && hasSearched" class="empty-results">
      <el-empty description="未找到相关文献">
        <el-button type="primary" @click="resetSearch">重新搜索</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { searchApi } from '@/api/search'
import { literatureApi } from '@/api/literature'
import type { SearchRequest, SearchResultItem, PageResult, AdvancedSearchCriteria } from '@/api/search'

// 响应式数据
const router = useRouter()
const searching = ref(false)
const hasSearched = ref(false)
const searchKeyword = ref('')
const searchType = ref('all')
const sortField = ref('relevance')

const searchResults = ref<SearchResultItem[]>([])
const searchHistory = ref<string[]>([])
const hotKeywords = ref<string[]>([
  '癌症治疗',
  '基因编辑',
  '免疫疗法',
  '药物研发',
  '临床试验',
  '医学影像',
  '人工智能',
  '精准医疗'
])

const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 方法
const performSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  searching.value = true
  hasSearched.value = true

  try {
    // 构造高级搜索条件
    let advanced: AdvancedSearchCriteria | undefined = undefined;
    if (searchType.value !== 'all') {
      advanced = {} as AdvancedSearchCriteria;
      if (searchType.value === 'title') {
        advanced.title = searchKeyword.value;
      } else if (searchType.value === 'author') {
        advanced.authors = searchKeyword.value;
      } else if (searchType.value === 'keyword') {
        advanced.keywords = searchKeyword.value;
      }
    }

    const request: SearchRequest = {
      keyword: searchType.value === 'all' ? searchKeyword.value : '',
      advanced: advanced,
      current: pagination.value.current,
      size: pagination.value.size,
      sortField: sortField.value
    }

    const response: PageResult<SearchResultItem> = await searchApi.searchLiterature(request)
    
    searchResults.value = response.records
    pagination.value.total = response.total
    
    // 添加到搜索历史
    addToHistory(searchKeyword.value)
    
    searching.value = false
  } catch (error) {
    ElMessage.error('搜索失败: ' + (error instanceof Error ? error.message : '系统异常，请稍后重试'))
    searching.value = false
  }
}

const searchByKeyword = (keyword: string) => {
  searchKeyword.value = keyword
  searchType.value = 'all'
  pagination.value.current = 1
  performSearch()
}

const addToHistory = (keyword: string) => {
  // 移除重复项
  const index = searchHistory.value.indexOf(keyword)
  if (index > -1) {
    searchHistory.value.splice(index, 1)
  }
  
  // 添加到开头
  searchHistory.value.unshift(keyword)
  
  // 限制历史记录数量
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }
}

const clearHistory = async () => {
  try {
    await ElMessageBox.confirm('确定要清空搜索历史吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await searchApi.clearSearchHistory()
    searchHistory.value = []
    ElMessage.success('搜索历史已清空')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const loadSearchHistory = async () => {
  try {
    searchHistory.value = await searchApi.getSearchHistory()
  } catch (error) {
    console.error('加载搜索历史失败:', error)
  }
}

const loadHotKeywords = async () => {
  try {
    hotKeywords.value = await searchApi.getHotKeywords()
  } catch (error) {
    console.error('加载热门关键词失败:', error)
  }
}

const viewDetail = (id: number) => {
  router.push(`/literature/detail/${id}`)
}

const resetSearch = () => {
  searchKeyword.value = ''
  searchResults.value = []
  hasSearched.value = false
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  performSearch()
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
  performSearch()
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleDateString('zh-CN');
}

// 生命周期
onMounted(() => {
  loadSearchHistory();
  loadHotKeywords();
});
</script>

<style scoped>
.search-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
}

.search-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 28px;
}

.search-header p {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

.search-box {
  max-width: 800px;
  margin: 0 auto 30px;
}

.search-assist {
  margin-bottom: 30px;
}

.hot-search-card, .history-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hot-keywords, .search-history {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
}

.hot-keyword, .history-keyword {
  cursor: pointer;
  transition: transform 0.2s;
}

.hot-keyword:hover, .history-keyword:hover {
  transform: scale(1.05);
}

.empty-history {
  color: #909399;
  font-size: 14px;
  padding: 20px 0;
  text-align: center;
}

.search-results {
  margin-bottom: 30px;
}

.results-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.result-item:hover {
  background-color: #f5f7fa;
  margin: 0 -20px;
  padding-left: 20px;
  padding-right: 20px;
}

.result-item:last-child {
  border-bottom: none;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.result-authors {
  color: #606266;
  margin-bottom: 10px;
  font-size: 14px;
}

.result-abstract {
  color: #909399;
  margin-bottom: 15px;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.journal {
  font-weight: 500;
}

.date {
  flex-shrink: 0;
}

.keywords {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-results {
  padding: 60px 0;
}

@media (max-width: 768px) {
  .search-container {
    padding: 10px;
  }
  
  .search-header h2 {
    font-size: 24px;
  }
  
  .search-assist .el-col {
    margin-bottom: 20px;
  }
  
  .results-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
}
</style>